import React, {useCallback, useContext, useEffect, useRef, useState} from 'react';
import { Button, Space } from "antd";

import { Ctx } from "../../ctx";
import { getLocalNetworkInfo } from "./LocalNetworkInfo";
import { getMockAttackResult } from "./MockAttackResult";

export interface NetworkToolBarProps{}

export const NetworkToolBar: React.FC<NetworkToolBarProps> = () => {
    const {localNetworkStore, initData, attacking, handleMockAttack} = useNetworkToolBar();

    return <div className="absolute" style={{left: 10, top: 10}}>
        <Space.Compact>
            {initData.localNetworkDeviceList.map(({label, value}) => <Button
                key={value}
                onClick={() => localNetworkStore.addDevice(value)}
            >{label}</Button>)}
            <Button onClick={() => localNetworkStore.addConnectLine()}>连接光缆</Button>
        </Space.Compact>

        <Space.Compact style={{marginLeft: 10}}>
            <Button onClick={() => getLocalNetworkInfo(localNetworkStore)}>局域网信息</Button>
            <Button onClick={handleMockAttack}>{attacking ? "停止攻击" : "模拟攻击"}</Button>
        </Space.Compact>
    </div>
}

const useNetworkToolBar = () => {
    const { simulationStore } = useContext(Ctx);
    const {localNetworkStore, initData} = simulationStore;
    const [attacking, setAttacking] = useState(false);
    const disposeMockAttackRef = useRef<Function>()

    useEffect(() => {
        return () => {
            if(localNetworkStore) localNetworkStore.destroy();
            if(disposeMockAttackRef.current) disposeMockAttackRef.current();
        }
    }, [localNetworkStore])

    const handleMockAttack = useCallback(() => {
        if(attacking) {
            if (disposeMockAttackRef.current) {
                disposeMockAttackRef.current();
                setAttacking(!attacking);
                getMockAttackResult(localNetworkStore);
            }
        }else{
            setAttacking(!attacking);
            setTimeout(() => {
                const dispose = localNetworkStore.mockAttack();
                if(!dispose) {
                    setAttacking(false);
                }else{
                    disposeMockAttackRef.current = dispose;
                }
            })
        }
    }, [attacking])

    return { localNetworkStore, initData, attacking, handleMockAttack }
}
